package org.example.product.service;

import lombok.extern.slf4j.Slf4j;
import org.example.product.api.ProductApi;
import org.example.product.data.entity.ProductEntity;
import org.example.product.data.view.ProductInfo;
import org.example.product.service.storage.ProductEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ProductService implements ProductApi {

    @Autowired
    private ProductEntityMapper productEntityMapper;

    @Override
    public ProductInfo addProduct(ProductInfo productInfo) {

        ProductEntity productEntity = transformFrom(productInfo);

        Integer result = productEntityMapper.insertProduct(productEntity);

        if(1 != result){
            return null;

        }

        return transformTo(productEntity);

    }

    @Override
    public ProductInfo getProduct(ProductInfo productInfo) {

        ProductEntity productEntity = productEntityMapper.selectProductById(productInfo.getId());

        if(null == productEntity){
            return null;

        }

        return transformTo(productEntity);

    }

    @Override
    public ProductInfo updateProduct(ProductInfo productInfo) {

        ProductEntity productEntity = transformFrom(productInfo);

        Integer result = productEntityMapper.insertProduct(productEntity);

        ProductEntity updatedProductEntity = productEntityMapper.selectProductById(productInfo.getId());

        if(null == result){
            return null;

        }

        return transformTo(updatedProductEntity);

    }

    private ProductEntity transformFrom(ProductInfo productInfo){

        ProductEntity productEntity = new ProductEntity();

        productEntity.setId(productInfo.getId());
        productEntity.setCode(productInfo.getCode());
        productEntity.setName(productInfo.getName());
        productEntity.setProduceTimestamp(productInfo.getProduceTimestamp());

        return productEntity;

    }

    private ProductInfo transformTo(ProductEntity productEntity){

        ProductInfo productInfo = new ProductInfo();

        productInfo.setId(productEntity.getId());
        productInfo.setCode(productEntity.getCode());
        productInfo.setName(productEntity.getName());
        productInfo.setProduceTimestamp(productEntity.getProduceTimestamp());

        return productInfo;

    }

}
